#include "cam.c"
#include "aly.c"
#include <WiFi.h>
#include <PubSubClient.h>

WiFiClient espClient;
PubSubClient  client(espClient);
// 初始化 wifi 连接
void wifiInit(const char *ssid, const char *passphrase)
{
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, passphrase);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(1000);
        Serial.print(".");
    }
    Serial.println("Connected to AP");
}
void mqttCheckConnect()
{
  while (!client.connected())
  {
    Serial.println("Connecting to MQTT Server ...");
    if (client.connect(CLIENT_ID, MQTT_USRNAME, MQTT_PASSWD))
    {
      Serial.println("MQTT Connected!");
 
    }
    else
    {
      Serial.print("MQTT Connect err:");
      Serial.println(client.state());
      delay(5000);
    }
  }
}
void pubMsg(char *msg)
{
    boolean d = client.publish(PubTopic, msg);
    if(d){
      Serial.println("publish success"); 
    }else{
      Serial.println("publish fail"); 
    }
}
void pubData(camera_fb_t *fd)
{
    client.beginPublish(PubTopic, fd->len, false);
    client.write(fd->buf, fd->len);
    client.endPublish();
}
void aliyun_connect(){
    wifiInit(WIFI_SSID, WIFI_PASSWD);//连接WIFI
    client.setServer(MQTT_SERVER, MQTT_PORT);
    //client.setCallback(callback); //用于接收服务器接收的数据
    mqttCheckConnect();
    client.subscribe(PubTopic);
    Serial.println("tpoic connecting is ok");   
    //pubMsg("Hello,I'm m_camcar!");
  
}
//网络数据接受回调函数
void callback(char *topic, byte *payload, unsigned int length)
{
  //Serial.print("Message arrived [");
  //Serial.print(topic);
  //Serial.print("] ");
  payload[length] = '\0';
  Serial.println((char *)payload);
  if(strstr((char *)payload, "DOG_W") != NULL){
    //Serial.println("walk forward");
  }
  else if(strstr((char *)payload, "DOG_OFF") != NULL){
    //Serial.println("stop");
  }
  else{
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  //联接阿里云
  aliyun_connect();
  cam_init();
}
int i = 0;
void loop() {
  // put your main code here, to run repeatedly:
  
  client.loop();  //保持与阿里云的连接
  delay(20);
  camera_fb_t *fb_cam = esp_camera_fb_get();
  if(!fb_cam){
    Serial.println("cam fb get error!");
  }
  else{
    Serial.println(i++);
    //Serial.write(fb_cam->buf, fb_cam->len);
    //Serial.println("len:");
    //Serial.printf("%d",fb_cam->len);
    pubData(fb_cam);
    esp_camera_fb_return(fb_cam);
  }
}
